<style lang="scss" scoped>
  .status-3{ color: #07c160; }
  .modal-box{
    padding: .2rem .4rem;
    input,textarea{
      padding: .2rem;
      outline: none;
      border: 1px solid #e9e9e9;
      background-color: #fff;
      border-radius: 4px;
      width: 100%;
      min-height: .64rem;
    }
  }
  .cert-tips{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: .24rem;
    color: #666;
    padding: .2rem 0;
  }
  .cert-submit{
    margin: 0 .2rem;
  }
</style>

<template>
  <div class="container hasNav">
    <van-nav-bar :title="title" left-arrow left-text="返回" @click-left="$router.back()" fixed />

    <div class="cert-auth-box">
      <!-- 陪诊 -->
      <template v-if="type === 1">
        <template v-if="isPeizhenAuthed">
          <van-form
              ref="pzForm"
              input-align="right">
            <van-field
                readonly
                label="我能陪诊"
            >
              <template #input>
                <div class="status-3">已认证</div>
              </template>
            </van-field>
            <van-field
                readonly
                label="身份证号"
                :value="form.idCard"
            />
            <van-field
                readonly
                label="护士证号"
                :value="form.hsCard"
            />
            <van-field
                readonly
                label="医院"
                :value="form.hospName"
            />
            <van-field
                readonly
                label="科室"
                :value="form.deptTwoName"
            />
            <van-field
                readonly
                label="职称"
                :value="form.jobTitleName"
            />
          </van-form>
        </template>
        <template v-else>
          <van-form
              ref="pzForm"
              :show-error="false"
              :show-error-message="false"
              input-align="right">
            <van-field
                name="idCard"
                label="身份证号"
                v-model.trim="form.idCard"
                :rules="[{ required: true, message: '请填写身份证号' }]"
                placeholder="请输入身份证号"
                :maxlength="18"
            />
            <van-field
                name="hsCard"
                label="护士证号"
                v-model.trim="form.hsCard"
                :rules="[{ required: true, message: '请填写护士证号' }]"
                placeholder="请输入护士证号"
                :maxlength="12"
            />
            <van-field
                clickable
                readonly
                name="hospName"
                label="医院"
                :value="form.hospName"
                :rules="[{ required: true, message: '请选择医院' }]"
                placeholder="请选择"
                @click="showHospSelector"
                is-link
            />
            <van-field
                clickable
                readonly
                name="deptTwoName"
                label="科室"
                :value="form.deptTwoName"
                :rules="[{ required: true, message: '请选择科室' }]"
                placeholder="请选择"
                @click="showDeptSelector"
                is-link
            />
            <van-field
                clickable
                readonly
                name="jobTitleName"
                label="职称"
                :value="form.jobTitleName"
                :rules="[{ required: true, message: '请选择职称' }]"
                placeholder="请选择"
                @click="showTitleSelector"
                is-link
            />
          </van-form>

          <SingleUpload
              ref="hospCardFront"
              :image.sync="form.hospPic"
              :max-size="5"
              @handle-file="handleFile($event, 'hospFile')"
              title="请上传医院工牌"></SingleUpload>
          <div class="cert-tips">
            您的证件号码我们只作认证使用，不作任何其他
            <br>
            用途，会为您绝对保密。
          </div>
          <div class="cert-submit">
            <van-button block type="default" color="#179AFE" @click="onSubmitPeizhen">确定</van-button>
          </div>
        </template>
      </template>

      <!-- 陪护 -->
      <template v-else>
        <template v-if="isPeihuAuthed">
          <van-form
              ref="pzForm"
              input-align="right">
            <van-field
                readonly
                label="我能陪护"
            >
              <template #input>
                <div class="status-3">已认证</div>
              </template>
            </van-field>
            <van-field
                readonly
                label="所在城市"
                :value="form.cityName"
            />
            <van-field
                readonly
                label="身份证号"
                :value="form.idCard"
                :maxlength="18"
            />
          </van-form>

          <SingleUpload
              ref="nursingCardFront"
              :image.sync="form.hgPic2"
              :readonly="true"
              title="护工证"></SingleUpload>
        </template>
        <template v-else>
          <van-form
              ref="phForm"
              input-align="right"
          >
            <van-field
                clickable
                readonly
                name="city"
                label="所在城市"
                :value="form.cityName"
                placeholder="请选择"
                @click="showCitySelector"
                is-link
            />
            <van-field
                name="idCard"
                label="身份证号"
                v-model.trim="form.idCard"
                placeholder="请输入身份证号"
            />
          </van-form>
          <SingleUpload
              ref="nursingCardFront"
              :image.sync="form.hgPic1"
              :max-size="5"
              @handle-file="handleFile($event, 'hgFile1')"
              title="请上传身份证正面照"></SingleUpload>
          <SingleUpload
              ref="nursingCardBack"
              :image.sync="form.hgPic2"
              :max-size="5"
              @handle-file="handleFile($event, 'hgFile2')"
              title="请上传护工证正面照"></SingleUpload>

          <div class="cert-tips">
            您的证件号码我们只作认证使用，不作任何其他
            <br>
            用途，会为您绝对保密。
          </div>

          <div class="cert-submit">
            <van-button block type="default" color="#179AFE" @click="onSubmitPeihu">提交审核</van-button>
          </div>
        </template>
      </template>
    </div>

    <!-- 城市选择 -->
    <CascaderSelector
        :title="cascaderTitle"
        :key-name="cascaderKey"
        ref="CascaderSelector"
        @on-change="handleCascaderChange"
        @on-finish="handleCascaderFinish"
    ></CascaderSelector>

    <!-- 自定义 -->
    <van-dialog
        v-model="showCustomHospModal"
        title="请填写自定义医院"
        @confirm="handleConfirm"
        @close="handleClose"
        show-cancel-button>
      <div class="modal-box">
        <input
            v-model="customHospName"
            type="text"
            maxlength="50"
            placeholder="自定义医院名称">
      </div>
    </van-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import CascaderSelector from '../../components/CascaderSelector.vue';
  import SingleUpload from '../../components/SingleUpload.vue';

  import {
    getProvinces,
    getCitys,
    getHospitals,
    getDeptBig,
    getDeptSmall,
    getJobTitle,
    savePeizhenAuth,
    savePeihuAuth,
    getPeizhenAuth,
    getPeihuAuth
  } from "../../api/user";
  import { fileUrl } from '../../api/index';

  export default {
    name: 'CertAuth',
    components: {
      CascaderSelector,
      SingleUpload
    },
    data() {
      return {
        fileUrl,
        id: null,
        title: '我能陪诊认证',
        type: 1, // 1 陪诊 2 陪护
        form: {
          city: null,
          cityName: null,
          hospPic: null,
          hospFile: null,
          hgPic1: null,
          hgPic2: null,
          hgFile1: null,
          hgFile2: null,
          idCard: null,
          hsCard: null,
          hosp: null,
          hospName: null,
          deptOne: null,
          deptTwo: null,
          deptTwoName: null,
          jobTitle: null,
          jobTitleName: null,
        },
        cascaderKey: 'city',
        cascaderTitle: '请选择城市',
        showCustomHospModal: false,
        customHospName: ''
      };
    },
    mounted() {
      this.id = this.$route.params.id || null;
      this.type = +this.$route.query.type;
      if(this.type === 1) {
        this.title = '我能陪诊认证'
        this.getPeizhenAuth();
      } else {
        this.title = '我能陪护认证'
        this.getPeihuAuth();
      }
    },
    computed: {
      ...mapGetters(['userInfo']),
      // 是否已陪诊认证
      isPeizhenAuthed() {
        return this.userInfo.authstatus === 3
      },
      // 是否已陪护认证
      isPeihuAuthed() {
        return this.userInfo.chaperonageAuthStatus === 3
      }
    },
    methods: {
      async showCitySelector() {
        const data = await this.getProvinces();
        this.cascaderKey = 'city';
        this.cascaderTitle = '请选择城市';
        this.$refs.CascaderSelector.show(data);
      },
      async showHospSelector() {
        const data = await this.getProvinces();
        this.cascaderKey = 'hospital';
        this.cascaderTitle = '请选择医院';
        this.$refs.CascaderSelector.show(data);
      },
      async showDeptSelector() {
        const data = await this.getDeptBig();
        this.cascaderKey = 'department';
        this.cascaderTitle = '请选择科室';
        this.$refs.CascaderSelector.show(data);
      },
      async showTitleSelector() {
        const data = await this.getJobTitle();
        this.cascaderKey = 'title';
        this.cascaderTitle = '请选择职称';
        this.$refs.CascaderSelector.show(data);
      },
      async handleCascaderChange(data) {
        // 城市
        if(this.cascaderKey === 'city') {
          if(data.level === 0) {
            const citys = await this.getCitys(data.value);
            this.$refs.CascaderSelector.getDatas(data.value, citys);
          }
        }
        // 医院
        if(this.cascaderKey === 'hospital') {
          if(data.level === 0) {
            const citys = await this.getCitys(data.value, true);
            this.$refs.CascaderSelector.getDatas(data.value, citys);
          }
          if(data.level === 1) {
            const hospitals = await this.getHospitals(data.value)
            this.$refs.CascaderSelector.getDatas(data.value, hospitals);
          }
          // 如果是自定义
          if(data.value === -1) {
            this.showCustomHospModal = true;

          }
        }
        // 科室
        if(this.cascaderKey === 'department') {
          if(data.level === 0) {
            const depts = await this.getDeptSmall(data.value)
            this.$refs.CascaderSelector.getDatas(data.value, depts);
          }
        }
      },
      async handleCascaderFinish(data) {
        let last = data[data.length - 1];
        if(this.cascaderKey === 'city') {
          this.form.cityName = last.text;
          this.form.city = last.value;
        }
        if(this.cascaderKey === 'hospital') {
          // 如果不为自定义
          if(last.value !== -1) {
            this.form.hospName = last.text;
          }
          this.form.hosp = last.value;
          this.form.city = data[1].value;
          this.form.cityName = data[1].text;
        }
        if(this.cascaderKey === 'department') {
          this.form.deptOne = data[0].value;
          this.form.deptTwo = data[1].value;
          this.form.deptTwoName = data[1].text;
        }
        if(this.cascaderKey === 'title') {
          this.form.jobTitleName = last.text;
          this.form.jobTitle = last.value;
        }
      },
      async getProvinces() {
        const { provinces } = await getProvinces()
        return provinces.map(k => {
          return {
            text: k.provinceName,
            value: k.provinceId,
            children: []
          }
        })
      },
      async getCitys(provinceId, hasChild) {
        const { areas } = await getCitys(provinceId)
        return areas.map(k => {
          return hasChild ? {
            text: k.areaName,
            value: k.areaId,
            children: []
          } : {
            text: k.areaName,
            value: k.areaId
          }
        })
      },
      async getHospitals(cityId) {
        const { hospitals } = await getHospitals(cityId)
        return hospitals.map(k => {
          return {
            text: k.hospitalName,
            value: k.hospitalId
          }
        })
      },
      async getDeptBig() {
        const { departments } = await getDeptBig()
        return departments.map(k => {
          return {
            text: k.departmentName,
            value: k.departmentId,
            children: []
          }
        })
      },
      async getDeptSmall(departmentId) {
        const { departments } = await getDeptSmall(departmentId)
        return departments.map(k => {
          return {
            text: k.departmentName,
            value: k.departmentId
          }
        })
      },
      async getJobTitle(departmentId) {
        const { jobtitles } = await getJobTitle(departmentId)
        return jobtitles.map(k => {
          return {
            text: k.jobtitleName,
            value: k.jobtitleId
          }
        })
      },
      handleConfirm() {
        console.log('点击确认')
        this.form.hospName = this.customHospName
      },
      handleClose() {
        this.customHospName = '';
      },
      onSubmitPeizhen() {
        this.$refs.pzForm.validate().then(async () => {
          if(!this.form.hospFile) {
            return this.$toast('请上传医院工牌')
          }
          if(this.form.idCard.length !== 18) {
            return this.$toast('请输入18位正确的身份证号码')
          }
          if(this.form.hsCard.length !== 12) {
            return this.$toast('请输入12位正确的护士证号')
          }

          // 验证通过
          let formData = new FormData();
          formData.append('membersIdCard', this.form.idCard)
          formData.append('nurseNumber', this.form.hsCard)
          formData.append('hospitalId', this.form.hosp)
          formData.append('hospital', this.form.hospName)
          formData.append('areaId', this.form.city)
          formData.append('areaName', this.form.cityName)
          formData.append('department', this.form.deptTwoName)
          formData.append('oneDepartmentId', this.form.deptOne)
          formData.append('twoDepartmentId', this.form.deptTwo)
          formData.append('jobTitle', this.form.jobTitleName)
          formData.append('identifyphoto', this.form.hospFile)

          const { errorcode, errormsg } = await savePeizhenAuth(formData)
          if(!errorcode) {
            let userInfo = JSON.parse(JSON.stringify(this.userInfo))
            userInfo.authstatus = 1;
            this.$store.commit('setUserInfo', userInfo);
            this.$toast('陪诊认证提交成功!')
            // if(this.form.hospFile_base64) {
            //   localStorage.setItem('hospFile', this.form.hospFile_base64)
            // }
          } else {
            this.$toast(errormsg)
          }
        }, err => {
          if(err && err.length) {
            this.$toast(err[0].message)
          }
        })
      },
      onSubmitPeihu() {
        this.$refs.phForm.validate().then(async () => {
          if(this.form.idCard.length !== 18) {
            return this.$toast('请输入18位正确的身份证号码')
          }
          if(!this.form.hgFile1) {
            return this.$toast('请上传身份证正面照')
          }
          if(!this.form.hgFile2) {
            return this.$toast('请上传护工证正面照')
          }

          // 验证通过
          let formData = new FormData();
          formData.append('membersIdCard', this.form.idCard)
          formData.append('cityId', this.form.city)
          formData.append('cityName', this.form.cityName)
          formData.append('identifyphoto', this.form.hgFile1)
          formData.append('healthPicture', this.form.hgFile2)

          const { errorcode, errormsg } = await savePeihuAuth(formData)
          if(!errorcode) {
            let userInfo = JSON.parse(JSON.stringify(this.userInfo))
            userInfo.chaperonageAuthStatus = 1;
            this.$store.commit('setUserInfo', userInfo);
            this.$toast('陪护认证提交成功!')
            // if(this.form.hgFile1_base64) {
            //   localStorage.setItem('hgFile1', this.form.hgFile1_base64)
            // }
            // if(this.form.hgFile2_base64) {
            //   localStorage.setItem('hgFile2', this.form.hgFile2_base64)
            // }
          } else {
            this.$toast(errormsg)
          }
        }, err => {
          if(err && err.length) {
            this.$toast(err[0].message)
          }
        })
      },
      async getPeizhenAuth() {
        const { info } = await getPeizhenAuth();
        this.form = {
          idCard: info.membersIdCard,
          hsCard: info.nurseNumber,
          hosp: info.hospitalId,
          hospName: info.hospital,
          city: info.areaId,
          cityName: info.areaName,
          deptOne: info.oneDepartmentId,
          deptTwo: info.twoDepartmentId,
          deptTwoName: info.department,
          jobTitleName: info.jobTitle,
          hospPic: !!info.identifyphoto ? this.fileUrl + info.identifyphoto : '',
          // hospFile: info.identifyphoto
        };
        const that = this;
        if(!!info.identifyphoto) {
          this.form.hospPic = this.fileUrl + info.identifyphoto
          this.getBase64(this.fileUrl + info.identifyphoto, (dataURL) => {
            that.form.hospFile = that.dataURLtoFile(dataURL, 'identifyphoto.jpg')
          })
        }

        // if(localStorage.getItem('hospFile')) {
        //   this.form.hospFile = this.dataURLtoFile(localStorage.getItem('hospFile'), 'identifyphoto.jpg')
        // }
      },
      async getPeihuAuth() {
        const { dataInfo } = await getPeihuAuth();
        this.form = {
          city: dataInfo.cityId,
          cityName: dataInfo.cityName,
          idCard: dataInfo.membersIdCard
        };
        if(this.isPeihuAuthed) {
          this.form.hgPic2 = !!dataInfo.healthPicture ? this.fileUrl + dataInfo.healthPicture : ''
        }

        const that = this;
        if(!!dataInfo.identifyphoto) {
          this.form.hgPic1 = this.fileUrl + dataInfo.identifyphoto
          this.getBase64(this.fileUrl + dataInfo.identifyphoto, (dataURL) => {
            that.form.hgFile1 = that.dataURLtoFile(dataURL, 'identifyphoto.jpg')
          })
        }

        if(!!dataInfo.healthPicture) {
          this.form.hgPic2 = this.fileUrl + dataInfo.healthPicture
          this.getBase64(this.fileUrl + dataInfo.healthPicture, (dataURL) => {
            that.form.hgFile2 = that.dataURLtoFile(dataURL, 'healthPicture.jpg')
          })
        }

        // if(localStorage.getItem('hgFile1')) {
        //   this.form.hgFile1 = this.dataURLtoFile(localStorage.getItem('hgFile1'), 'identifyphoto.jpg')
        // }
        // if(localStorage.getItem('hgFile2')) {
        //   this.form.hgFile2 = this.dataURLtoFile(localStorage.getItem('hgFile2'), 'healthPicture.jpg')
        // }
      },
      handleFile(file, keyName) {
        this.form[keyName] = file.file;

        if(keyName === 'hospFile') {
          delete this.form.hospPic
          this.$set(this.form, 'hospPic', file.content)
        }
        if(keyName === 'hgFile1') {
          delete this.form.hgPic1
          this.$set(this.form, 'hgPic1', file.content)
        }
        if(keyName === 'hgFile2') {
          delete this.form.hgPic2
          this.$set(this.form, 'hgPic2', file.content)
        }
      },
      getBase64(url, callback) {
        //通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片，相比 createElement() 创建 <img> 省去了 append()，也就避免了文档冗余和污染
        let Img = new Image(),
          dataURL = '';
        Img.src = url +"?v=" + Math.random(); // 处理缓存,fix缓存bug,有缓存，浏览器会报错;
        Img.setAttribute("crossOrigin", 'Anonymous') // 解决控制台跨域报错的问题
        Img.onload = function () { //要先确保图片完整获取到，这是个异步事件
          var canvas = document.createElement("canvas"), //创建canvas元素
            width = Img.width, //确保canvas的尺寸和图片一样
            height = Img.height;
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
          callback ? callback(dataURL) : null; //调用回调函数
        };
      },
      dataURLtoFile(dataurl, filename) {
        if(!dataurl) return;
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
      }
    }
  };
</script>
